<template>
  <div class="main">
    <el-card>
      <h3>关联用户端账号</h3>
      <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      class="demo-ruleForm"
    >

    <el-form-item label="关联用户账号" prop="userId">
      <el-select
        clearable
        v-model="ruleForm.userId"
        filterable
        remote
        reserve-keyword
        placeholder="请输入用户注册手机"
        :remote-method="remoteMethod"
        :loading="loading">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <!-- <el-select
      clearable
      style="margin-left:10px"
      v-model="ruleForm.userId"

      filterable
      placeholder="请输入用户注册手机"
      :loading="loading">
      <el-option
        v-for="item in userList"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-select > -->
    </el-form-item> 
  
      <!-- <el-form-item label="关联用户账号" prop="userId">
        <el-input v-model="ruleForm.userId"></el-input>
      </el-form-item> -->
    <!-- </el-card> -->
    <!-- <el-card>
      <h3>申请人信息</h3>
      <el-descriptions title="">
        <el-descriptions-item label="申请人">张三</el-descriptions-item>
        <el-descriptions-item label="申请城市"
          >江西省南昌市</el-descriptions-item
        >
        <el-descriptions-item label="关联用户账号"
          >李四13213212313</el-descriptions-item
        >
        <el-descriptions-item label="联系电话"
          >13665552569</el-descriptions-item
        >
        <el-descriptions-item label="申请时间">2024-1-2</el-descriptions-item>
      </el-descriptions>
    </el-card> -->
    <!-- <el-card> -->
      <div class="line"></div>
      <h3>基础设施</h3>
      
        <el-form-item label="门店名称" prop="storeName">
          <el-input v-model="ruleForm.storeName"></el-input>
        </el-form-item>
        <!-- {{ruleForm.AddressObj}} -->
        <el-form-item label="门店地址" prop="detailAddress">
            <el-cascader :options="addressList" @change="handleChange" v-model="ruleForm.AddressObj" :props="defaultParams" clearable></el-cascader>
            <p style="margin-left:10px;" class="map" @click="dialogVisible = true">
                {{ruleForm.detailAddress}}
                <i class="el-icon-map-location" />
            </p>
        </el-form-item>
        <el-form-item label="门店等级" prop="gradeValue">
          <el-select v-model="ruleForm.gradeValue" @change="changeGrade" clearable placeholder="请选择">
            <el-option
              v-for="item in shopGradeList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-select
          style="margin-left:10px;"
            clearable
            v-model="ruleForm.parentId"
            :disabled='!ruleForm.gradeValue||ruleForm.gradeValue==2'
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethodTwo"
            :loading="loading">
            <el-option
              v-for="item in optionsTwo"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <!-- <el-select
            clearable
            style="margin-left:10px"
            v-model="ruleForm.parentId"
            :disabled='!ruleForm.gradeValue||ruleForm.gradeValue==2'
            filterable
            placeholder="请选择上级"
            :loading="loading">
            <el-option
              v-for="item in parentStore"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select > -->
          <!-- <el-select v-model="ruleForm.parentId" placeholder="请选择上级">
            <el-option label="区域一" value="1"></el-option>
            <el-option label="区域二" value="2"></el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="营业时间" prop="businessHours">
          <el-input v-model="ruleForm.businessHours"></el-input>
        </el-form-item>
        <el-form-item label="门店照片" prop="logo">
          <image-upload :limit="1" v-model="ruleForm.logo" />
        </el-form-item>
        <el-form-item label="负责人" prop="directorName">
          <el-input v-model="ruleForm.directorName"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="directorPhone">
          <el-input v-model="ruleForm.directorPhone"></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
        <h3>资质照片</h3>
        <div class="img-list">
            <div class="img-item">
                <image-upload :limit="1" v-model="ruleForm.licenseImage" :isShowTip='false' />
                <p>营业执照</p>
            </div>
            <div class="img-item">
                <image-upload :limit="1" v-model="ruleForm.healthImage" :isShowTip='false'  />
                <p>卫生许可</p>
            </div>
        </div>
    </el-card>
    <el-card>
        <div class="flex-box">
            <el-button>取消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
        </div>
    </el-card>
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="700px"
        :before-close="handleClose">
        <el-amap-search-box
        :search-option="searchOption"
        :on-search-result="onSearchResult"
        />
        <!-- 地图 -->
        <el-amap
        class="amap-box"
        :zoom="amap.zoom"
        :center="amap.center"
        :plugin="amap.plugin"
        :events="amap.events"
        >
        <!-- 当前位置图标 -->
        <el-amap-marker
            v-for="(marker, index) in amap.markers"
            :key="'marker' + index"
            :position="marker.position"
        />
        <!-- 位置名称显示 -->
        <el-amap-text
            v-for="(marker, index) in amap.markers"
            :key="'text' + index"
            :text="marker.text"
            :offset="marker.offset"
            :position="marker.position"
        />
        </el-amap>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>
  </div>
  
</template>
  
  <script>
//初始数据
function getFormData() {
  return {
    lat: "39.909186",
    lon: "116.39746",
    orgAddr: "天安门",
    province: "",
    city: "",
    district: "",
  };
}
import {getStoreGrade,getParentStore,addStore,queryRelateUserInfo} from '@/api/shop'
import addressList from '@/utils/AddressData'
// import addressMap from '@/components/map' //引入组件
export default {
  name: "",
  components: {},

  props: {},

  data() {
    const vm = this;
    return {
      addressList:addressList,
      defaultParams:{
        label: "regionName",
        value: "regionId",
        children: "childs",
      },
      options: [],
      optionsTwo: [],
      userList:[],
      userListTwo:[],
      shopGradeList:[],
      parentStore:[],
      dialogVisible:false,
      loading: false,
      ruleForm: {
          userId:'',
          storeName:'',
          detailAddress:'',
          longitude:'',
          latitude:'',
          gradeValue:'',
          parentId:null,
          businessHours:'',
          logo:'',
          directorName:'',
          directorPhone:'',
          licenseImage:'',
          healthImage:'',
          provinceId:'',
          cityId:'',
          districtId:'',
          AddressObj:{}
        },
      rules: {
        id: [
            { required: true, message: '请输入关联账户', trigger: 'blur' },
        ],
        storeName: [
            { required: true, message: '请输入门店名称', trigger: 'blur' },
        ],
        detailAddress: [
            { required: true, message: '请输入门店地址', trigger: 'blur' },
        ],
        gradeValue: [
            { required: true, message: '请输入门店等级', trigger: 'blur' },
        ],
        businessHours: [
            { required: true, message: '请输入营业时间', trigger: 'blur' },
        ],
        logo: [
            { required: true, message: '请输入门店照片', trigger: 'blur' },
        ],
        userId: [
            { required: true, message: '请输入关联账户', trigger: 'blur' },
        ],
      },
      // form对象
      dataForm: getFormData(),
      // 地图搜索对象
      searchOption: {
        city: "全国",
        citylimit: true,
      },
      lng: 0,
      lat: 0,
      // 地图对象
      amap: {
        zoom: 16,
        center: [116.319802, 39.98294],
        events: {
          // 点击获取地址的数据
          click(e) {
            const { lng, lat } = e.lnglat;
            vm.dataForm.lon = lng;
            vm.ruleForm.latitude = lat;
            vm.ruleForm.longitude = lng;

            // 这里通过高德 SDK 完成。
            var geocoder = new AMap.Geocoder({
              radius: 100,
              extensions: "all",
            });
            geocoder.getAddress([lng, lat], function (status, result) {
              if (status === "complete" && result.info === "OK") {
                if (result && result.regeocode) {
                  console.log("点击获取地址的数据", result);
                  vm.ruleForm.detailAddress = result.regeocode.formattedAddress
                  vm.dataForm.orgAddr = result.regeocode.formattedAddress;
                  vm.dataForm.province =
                    result.regeocode.addressComponent.province;
                  vm.dataForm.city = result.regeocode.addressComponent.city;
                  vm.dataForm.district =
                    result.regeocode.addressComponent.district;
                  vm.dataForm.lat = lat ? lat.toString() : "";
                  vm.dataForm.lon = lng ? lng.toString() : "";
                  vm.amap.markers = [];
                  const obj = {
                    position: [lng, lat],
                    text: result.regeocode.formattedAddress,
                    offset: [0, 30],
                  };
                  vm.amap.markers.push(obj);
                  vm.sure();
                }
              }
            });
            vm.$nextTick();
          },
        },

        plugin: [
          {
            // 定位
            pName: "Geolocation",
            events: {
              init(o) {
                // o是高德地图定位插件实例
                o.getCurrentPosition((status, result) => {
                  console.log("定位：", result);
                  if (result && result.position) {
                    // 设置经度

                    vm.ruleForm.latitude = result.position.lng;
                    // 设置维度
                    vm.ruleForm.longitude = result.position.lat;
                    // 设置坐标
                    vm.amap.center = [vm.lng, vm.lat];
                    let op = {
                      position: [vm.lng, vm.lat],
                      text: result.formattedAddress,
                      offset: [0, 30],
                    };
                    vm.amap.markers.push(op);
                    // 页面渲染好后
                    vm.$nextTick();
                  }
                });
              },
            },
          },
        ],
        //
        markers: [],
      },
    };
  },

  watch: {},
  computed: {},
  methods: {
    onSearchResult(pois) {
      const vm = this;
      vm.amap.markers = [];
      let latSum = 0;
      let lngSum = 0;
      console.log("地图回调", pois);
      if (pois.length > 0) {
        pois.forEach((poi, index) => {
          const { lng, lat } = poi;
          if (index === 0) {
            lngSum = lng;
            latSum = lat;
            const obj = {
              position: [poi.lng, poi.lat],
              text: poi.name,
              offset: [0, 30],
            };
            vm.amap.markers.push(obj);
            console.log("地图搜索回调", poi);
            vm.ruleForm.detailAddress = poi.name
            vm.ruleForm.latitude = poi.lat ? poi.lat.toString() : "";
            vm.ruleForm.longitude = poi.lng ? poi.lng.toString() : "";
            // vm.dataForm.orgAddr = poi.name;
            // vm.dataForm.lat = poi.lat ? poi.lat.toString() : "";
            // vm.dataForm.lon = poi.lng ? poi.lng.toString() : "";
          }
        });
        vm.amap.center = [lngSum, latSum];
      }
    },
    remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          setTimeout(() => {
            this.loading = false;
          this.options = this.userList.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
    remoteMethodTwo(query) {
        if (query !== '') {
          this.loading = true;
          setTimeout(() => {
            this.loading = false;
          this.optionsTwo = this.parentStore.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
    handleChange(val){
      this.ruleForm.provinceId =  val[0]
      this.ruleForm.cityId =  val[1]
      this.ruleForm.districtId =  val[2]
    },
    // 提交方法
    sure() {
      const vm = this;
      this.$emit("updateLocation", vm.dataForm);
    },
    async getShopGradeList(){
     const res = await getStoreGrade();
     let dataNew = [];    //新数组
     res.data.map(item => {
          let obj = {
            value: item.gradeValue,
            label:item.gradeName
          }
          dataNew.push(obj);
      });
      this.shopGradeList = dataNew
    },
    async getParentStoreList(){
      this.loading = true;
      const res = await getParentStore();
      let dataNew = [];    //新数组
      res.data.map(item => {
            let obj = {
              value: item.id,
              label:item.storeName
            }
            dataNew.push(obj);
        });
      this.loading = false;
      this.parentStore = dataNew
    },
    handleClose(){
        this.dialogVisible = false
    },
    async getQueryRelateUserInfo(){
      this.loading = true;
      const res = await queryRelateUserInfo({phoneNumber:''});
      let dataNew = [];    //新数组
      res.data.map(item => {
            let obj = {
              value: item.userId,
              label:item.relateUser
            }
            dataNew.push(obj);
        });
      this.loading = false;
      this.userList = dataNew
    },
    submitForm(formName) {
      console.log(this.ruleForm)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            addStore(this.ruleForm).then(res=>{
              this.$message({
                  message: res.message,
                  type: 'success'
              });
              this.$router.push({path:'/shop/list'})
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      changeGrade(val){
        if(val==2){
          this.ruleForm.parentId = null
        }
        console.log(val)
      }
  },
  created() {
    this.getShopGradeList()
    this.getParentStoreList()
    this.getQueryRelateUserInfo()
    console.log(addressList,'addressList')
  },

  mounted() {

  },
};
</script>
  
  <style lang="scss" scoped>
h3 {
  position: relative;
  font-size: 16px;
  font-weight: normal;
  padding-left: 8px;
  margin-bottom: 20px;
}
h3::before {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 2px;
  height: 16px;
  background: #1890ff;
}
h3::after {
  content: "";
  display: block;
  position: absolute;
  width: calc(100% - 110px);
  height: 1px;
  background: #ddd;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}
.el-input--medium {
  width: 300px;
}

.amap-box {
  width: 100%;
  height: 500px;
}
.map{
    position: relative;
    min-width: 300px;
    padding: 0 30px 0 5px;
    box-sizing: border-box;
    
    display: inline-block;
    height: 36px;
    line-height: 36px;
    margin: 0;
    border: 1px solid #ddd;
    i{
        position: absolute;
        right: 5px;
        top: 0;
        transform: translateY(80%);
    }
}
.el-vue-search-box-container {
    position: relative;
    width: 100%;
    height: 45px;
    background: #fff;
    box-shadow: 0 2px 2px rgba(0,0,0,.15);
    border-radius: 2px 3px 3px 2px;
    z-index: 10;
    border: 1px solid #ddd;
    margin-bottom: 10px;
}
.img-list{
    display: flex;
    .img-item{
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin-left: 20px;
    }
}
::v-deep  .el-form-item__content{
  display: flex;
  align-items: center;
}
::v-deep  .el-upload--picture-card{
    width: 100px;
    height: 100px;
    line-height: 100px;
}
.flex-box{
    display: flex;
    justify-content: center;
  }
  .line{
    width: 120%;
    height: 10px;
    background: #f0f2f5;
    transform: translateX(-15%);
  }
  .el-card{
    margin-bottom: 10px;
  }
</style>